package com.da.lon.wang.xlg.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appkefu.lib.interfaces.KFAPIs;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.FixAddressActivity;
import com.da.lon.wang.xlg.activity.SettingInfoActivity;
import com.da.lon.wang.xlg.bean.AutoLoginBean;
import com.da.lon.wang.xlg.bean.AutoLoginBean.AutoLoginResult;
import com.da.lon.wang.xlg.bean.FirstEvent;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.RoundImageView;
import com.osell.selection.ui.common.SettingActivity;
import com.osell.selection.ui.common.WebViewActivity;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.io.File;

import de.greenrobot.event.EventBus;


public class MineFragment extends BaseFragment implements OnClickListener {
    String user_key;
    String user_name;
    String user_sex;
    AutoLoginResult result;
    private Context context;
    private RoundImageView photoImageView;
    private TextView beforeLogin;
    private LinearLayout afterLogin;
    private TextView balanceTextView;
    private LinearLayout intentloginLayout;
    private TextView nameTextView;
    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView textView4;
    private TextView textView5;
    private TextView textView6;
    private TextView textView7;
    private TextView textView8;
    private TextView textView9;
    private TextView textView10;
    private TextView textView11;
    private TextView textView12;
    private TextView ocoffee_mine_coupon;
    private TextView ocoffee_mine_help;
    private TextView ocoffee_mine_cash;
    private TextView ocoffee_mine_gift;
    private TextView ocoffee_mine_extend;
    private TextView mine_cash;
    private ImageView mine_vip_img;
    private TextView mine_vip_lev;
    private String points;
    private String vip_lev;
    private String vip_img;
    private LinearLayout mine_vip;
    private View view;
    private TextView ocoffee_mine_pfcg;
    private TextView ocoffee_mine_ms;
    private TextView tv_add_product;
    private TextView tv_my_products;
    private TextView tv_records;
    private ImageButton btn_go_to_setting;

    private SharedPreferences mUserInfoSp;

    public static void startChat(Context context, String storecode,
                                 String storename, String useraccount, String usernickname,
                                 String goodsImageurl, String goodstitledetail, String goodsprice,
                                 String goodsurl) {

        boolean isEcChat = true;

        if (TextUtils.isEmpty(storecode)) {
            storecode = "pxokakfq";
        }
        if (TextUtils.isEmpty(storename)) {
            storename = "客服对话";
        }
        if (TextUtils.isEmpty(useraccount)) {
            useraccount = "游客";
        }
        if (TextUtils.isEmpty(usernickname)) {
            usernickname = "游客";
        }
        if (TextUtils.isEmpty(goodsImageurl)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodstitledetail)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsprice)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsurl)) {
            isEcChat = false;
        }

        KFAPIs.setTagNickname(usernickname + "(" + useraccount + ")", context);
        if (!isEcChat) {
            KFAPIs.startChat(context, storecode, // 1.
                    storename,
                    null,
                    false,
                    5, // 5.
                    null, // 6.
                    null, // 7.
                    false, // 8.
                    isEcChat, null);
        } else {
            KFAPIs.startECChat(context, storecode, // 1.
                    // 客服工作组ID(请务必保证大小写一致)，请在管理后台分配
                    storename, // 2. 会话界面标题，可自定义
                    goodsurl, // 3.
                    false, // 4. 是否显示自定义菜单,如果设置为显示,请务必首先在管理后台设置自定义菜单,
                    5, // 5. 默认显示消息数量
                    null, // 6. 修改默认客服头像，如果不想修改默认头像，设置此参数为null
                    null, // 7. 修改默认用户头像, 如果不想修改默认头像，设置此参数为null
                    false, // 8. 是否开启机器人应答

                    true, // 9.是否显示商品布局
                    goodsImageurl, // 10.商品图片网址
                    goodstitledetail, // 11.商品描述详情
                    goodsprice, // 12.商品价格

                    goodsurl, goodsurl, isEcChat, null);
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserInfoSp = MyApplication.getInstance().getSharedPreferences("user_info", Context.MODE_PRIVATE);
    }

    public void onResume() {
        super.onResume();
        isLogin();
        MobclickAgent.onPageStart("MineFragment");
        MobclickAgent.onResume(getActivity());
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MineFragment");
        MobclickAgent.onPause(getActivity());
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup var2) {
        view = inflater.inflate(R.layout.xlg_mine_fragment, null);
        return view;
    }

    @Override
    protected void initView() {
        // TODO Auto-generated method stub
        context = getActivity();
        initView(view);

    }

    private void isLogin() {
        try {
            user_key = mUserInfoSp.getString("user_key", "");
            final String user_balance = PreferenceUtils.getInstance()
                    .getSettingStr(PreferencesConfig.USER_BALANCE, "");
            final String is_vip = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.IS_VIP, "");
            HttpLoader<AutoLoginBean> httpLoader = new HttpLoader<AutoLoginBean>(
                    context, XLGConstants.URL + "Login-memberinfo",
                    AutoLoginBean.class);
            AjaxParams params = new AjaxParams();
            params.put("user_key", mUserInfoSp.getString("user_key", ""));
            params.put("user_id", mUserInfoSp.getString("user_id", ""));
            params.put("token", XLGDataUtils.encrypt2MD5("Login" + "2015#$%" + "memberinfo"));
            params.put("device_type", "1");
            showInfo(result, user_balance, is_vip);
            httpLoader
                    .setManagerListener(new OnWebLoadListener<AutoLoginBean>() {

                        @Override
                        public void OnStart() {

                        }

                        @Override
                        public void OnError(String error) {
                        }

                        @Override
                        public void onSuccess(AutoLoginBean t) {
                            if (t != null && "000000".equals(t.getCode())
                                    && t.getResult() != null) {
                                points = t.getResult().getPoints();
                                vip_img = t.getResult().getRanklogo();
                                vip_lev = t.getResult().getRankname();
                                result = t.getResult();
                                showInfo(result, user_balance, is_vip);
                            }
                        }
                    });
            if (!TextUtils.isEmpty(user_key)) {
                httpLoader.loadData(params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showInfo(AutoLoginResult result, String user_balance, String is_vip) {
        try {
            if (result == null || !TextUtils.equals("true", result.getBinding())) {
                afterLogin.setVisibility(View.GONE);
                beforeLogin.setVisibility(View.VISIBLE);
                balanceTextView.setClickable(false);
                photoImageView.setClickable(false);
                mine_vip.setVisibility(View.GONE);
                photoImageView.setImageResource(R.drawable.ouka_home_photo_small);
                photoImageView.setScaleType(ScaleType.CENTER_INSIDE);

                intentloginLayout.setOnClickListener(v -> {
                    if (result != null) {
                        startActivity(new Intent(context, WebViewActivity.class).putExtra("url", result.getBinding_url()));
                    }
                });

            } else {
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.RANKLOGO, result.getRanklogo());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.RANKNAME, result.getRankname());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.POINTS, result.getPoints());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.HEAD_LOG, result.head_log);
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_BALANCE, result.balance);
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_NAME, result.getUserName());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.IS_VIP, result.is_vip);
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.HEAD_LOG, result.getHead_log());
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.USER_SEX, result.getSex());
                    PreferenceUtils.getInstance().SetSettingString(
                            "birthday",
                            result.getBirth_year() + "年"
                                    + result.getBirth_month() + "月"
                                    + result.getBirth_day() + "日");
                    PreferenceUtils.getInstance().SetSettingString(
                            "birth_year", result.getBirth_year());
                    PreferenceUtils.getInstance().SetSettingString(
                            "birth_month", result.getBirth_month());
                    PreferenceUtils.getInstance().SetSettingString("birth_day",
                            result.getBirth_day());
                String head_log = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.HEAD_LOG, "");
                user_name = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.USER_NAME, "");
                user_sex = PreferenceUtils.getInstance().getSettingStr(
                        PreferencesConfig.USER_SEX, "");
                afterLogin.setVisibility(View.VISIBLE);
                beforeLogin.setVisibility(View.GONE);
                nameTextView.setText(user_name);
                balanceTextView.setText(user_balance);
                intentloginLayout.setClickable(false);
                mine_cash.setText(getString(R.string.score, points));

                if (user_sex != null && !"".equals(user_sex) && isAdded()) {
                    Drawable manDrawable = getResources().getDrawable(
                            R.drawable.ouka_mine_man);
                    manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(),
                            manDrawable.getMinimumHeight());
                    Drawable womanDrawable = getResources().getDrawable(
                            R.drawable.ouka_mine_woman);
                    womanDrawable.setBounds(0, 0,
                            womanDrawable.getMinimumWidth(),
                            womanDrawable.getMinimumHeight());
                    if ("1".equals(user_sex)) {
                        nameTextView.setCompoundDrawables(null, null,
                                manDrawable, null);
                    } else if ("0".equals(user_sex)) {
                        nameTextView.setCompoundDrawables(null, null,
                                womanDrawable, null);
                    } else {
                        nameTextView.setCompoundDrawables(null, null, null,
                                null);
                    }
                } else {
                    nameTextView.setCompoundDrawables(null, null, null, null);
                }

                if (vip_lev != null && !"".equals(vip_lev) && vip_img != null
                        && !"".equals(vip_img.trim()) && !vip_img.isEmpty()) {
                    mine_vip.setVisibility(View.VISIBLE);
                    mine_vip_lev.setText(vip_lev);
                    MyApplication.loadImageByPicasso(context, vip_img, null, mine_vip_img, 0, 0, 1);
                } else {
                    mine_vip.setVisibility(View.GONE);
                }
                MyApplication.loadImageByPicasso(context, head_log, null, photoImageView, 120, 120, 1);
                photoImageView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (!MyApplication.isNetworkAvailable(context)) {
                            return;
                        }
                        Intent intent = new Intent(getActivity(),
                                SettingInfoActivity.class);
                        startActivity(intent);
                    }
                });

                balanceTextView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (!MyApplication.isNetworkAvailable(context)) {
                            return;
                        }
                        Intent intent = new Intent(context,
                                WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 800);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    public void onEventMainThread(FirstEvent event) {
        File msg = event.getMsg();
        MyApplication.loadImageByPicasso(context, null, msg, photoImageView, 50, 50, 1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView(View view) {
        photoImageView = (RoundImageView) view
                .findViewById(R.id.leftmenu_photo);
        beforeLogin = (TextView) view.findViewById(R.id.leftmenu_before_login);
        afterLogin = (LinearLayout) view
                .findViewById(R.id.leftmenu_after_login);
        balanceTextView = (TextView) view.findViewById(R.id.leftmenu_balance);
        intentloginLayout = (LinearLayout) view
                .findViewById(R.id.leftmenu_intent_login);
        nameTextView = (TextView) view.findViewById(R.id.leftmenu_username);

        textView1 = (TextView) view.findViewById(R.id.ocoffee_mine_dfk);
        textView2 = (TextView) view.findViewById(R.id.ocoffee_mine_dfh);
        textView3 = (TextView) view.findViewById(R.id.ocoffee_mine_dsh);
        textView4 = (TextView) view.findViewById(R.id.ocoffee_mine_dpj);
        textView5 = (TextView) view.findViewById(R.id.ocoffee_mine_thtk);
        textView6 = (TextView) view.findViewById(R.id.ocoffee_mine_wddd);
        textView7 = (TextView) view.findViewById(R.id.ocoffee_mine_scj);
        textView8 = (TextView) view.findViewById(R.id.ocoffee_mine_shdz);
        textView9 = (TextView) view.findViewById(R.id.ocoffee_mine_zhaq);
        textView10 = (TextView) view.findViewById(R.id.ocoffee_mine_yjfk);
        textView11 = (TextView) view.findViewById(R.id.ocoffee_mine_lxkf);
        textView12 = (TextView) view.findViewById(R.id.ocoffee_mine_xxzx);
        ocoffee_mine_pfcg = (TextView) view.findViewById(R.id.ocoffee_mine_pfcg);
        ocoffee_mine_coupon = (TextView) view
                .findViewById(R.id.ocoffee_mine_coupon);
        ocoffee_mine_help = (TextView) view
                .findViewById(R.id.ocoffee_mine_help);
        ocoffee_mine_cash = (TextView) view
                .findViewById(R.id.ocoffee_mine_cash);
        ocoffee_mine_gift = (TextView) view
                .findViewById(R.id.ocoffee_mine_gift);
        ocoffee_mine_extend = (TextView) view
                .findViewById(R.id.ocoffee_mine_extend);
        mine_cash = (TextView) view.findViewById(R.id.mine_cash);
        mine_vip_img = (ImageView) view.findViewById(R.id.mine_vip_img);
        mine_vip_lev = (TextView) view.findViewById(R.id.mine_vip_lev);
        mine_vip = (LinearLayout) view.findViewById(R.id.mine_vip);
        ocoffee_mine_ms = (TextView) view.findViewById(R.id.ocoffee_mine_ms);
        tv_add_product = (TextView) view.findViewById(R.id.tv_add_product);
        tv_my_products = (TextView) view.findViewById(R.id.tv_my_products);
        tv_records = (TextView) view.findViewById(R.id.tv_records);
        btn_go_to_setting = view.findViewById(R.id.btn_go_to_setting);

        ocoffee_mine_ms.setOnClickListener(this);
        ocoffee_mine_coupon.setOnClickListener(this);
        ocoffee_mine_help.setOnClickListener(this);
        ocoffee_mine_cash.setOnClickListener(this);
        ocoffee_mine_gift.setOnClickListener(this);
        ocoffee_mine_extend.setOnClickListener(this);
        textView1.setOnClickListener(this);
        textView2.setOnClickListener(this);
        textView3.setOnClickListener(this);
        textView4.setOnClickListener(this);
        textView5.setOnClickListener(this);
        textView6.setOnClickListener(this);
        textView7.setOnClickListener(this);
        textView8.setOnClickListener(this);
        textView9.setOnClickListener(this);
        textView10.setOnClickListener(this);
        textView11.setOnClickListener(this);
        textView12.setOnClickListener(this);
        mine_vip.setOnClickListener(this);
        ocoffee_mine_pfcg.setOnClickListener(this);
        btn_go_to_setting.setOnClickListener(this);
        tv_add_product.setOnClickListener(this);
        tv_my_products.setOnClickListener(this);
        tv_records.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (!MyApplication.isNetworkAvailable(context)) {
            return;
        }
        switch (v.getId()) {

            case R.id.ocoffee_mine_dfk:
                load(XLGConstants.WEB_URL + "Member-orders?oddis=dfk&get=nopay&notNeedFilter=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_dfh:
                load(XLGConstants.WEB_URL + "Member-orders?oddis=dfh&get=dfh&notNeedFilter=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_dsh:
                load(XLGConstants.WEB_URL + "Member-orders?oddis=dsh&sm=yes&get=s_sgow&notNeedFilter=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_dpj:
                load(XLGConstants.WEB_URL + "Member-orders?oddis=dpj&get=dpj&notNeedFilter=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_thtk:

                load(XLGConstants.WEB_URL + "Member-orders?oddis=tkz&get=tkz&notNeedFilter=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_wddd:
                load(XLGConstants.WEB_URL + "Member-orders.html");
                break;

            case R.id.ocoffee_mine_scj:
                load(XLGConstants.WEB_URL + "Member-profav.html");
                break;

            case R.id.ocoffee_mine_shdz:
                Intent intent8 = new Intent(context, FixAddressActivity.class);
                startActivity(intent8);
                break;

            case R.id.ocoffee_mine_zhaq:
                load(XLGConstants.WEB_URL + "Member-myanquan.html");
                break;

            case R.id.ocoffee_mine_yjfk:
                load(XLGConstants.WEB_URL + "Member-myyijian.html?notNeedFilter=1&qt=1&shop_id=" + MyApplication.getShopId());
                break;

            case R.id.ocoffee_mine_lxkf:
                try {
                    startChat(context, "", "", "", "", "", "", "", "");
                } catch (Exception e) {
                    Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.ocoffee_mine_xxzx:
                load(XLGConstants.WEB_URL + "Message-index.html");
                break;
            case R.id.ocoffee_mine_coupon:
                load(XLGConstants.WEB_URL + "Member-coupon.html");
                break;
            case R.id.ocoffee_mine_cash:
                load(XLGConstants.WEB_URL + "integral-index.html");
                break;
            case R.id.ocoffee_mine_help:
                Intent intent = new Intent(context, WebViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 001);
                bundle.putString("url", XLGConstants.WEB_URL + "Public-help.html");
                intent.putExtras(bundle);
                startActivity(intent);

                break;
            case R.id.ocoffee_mine_gift:
                load(XLGConstants.WEB_URL + "Member-package.html");
                break;
            case R.id.ocoffee_mine_extend:
                load(XLGConstants.WEB_URL + "Dictionary-become.html");
                break;
            case R.id.mine_vip:
                load(XLGConstants.WEB_URL + "Public-membergrade.html");
                break;
            case R.id.ocoffee_mine_pfcg:
                load(XLGConstants.WEB_URL + "Public-wholesale.html");

                break;
            case R.id.btn_go_to_setting:
                startActivity(new Intent(v.getContext(), SettingActivity.class));
                break;
            case R.id.tv_add_product:
                break;
            case R.id.tv_my_products:
                load(XLGConstants.WEB_URL + "member-myproduct.html");
                break;
            case R.id.tv_records:
                load(XLGConstants.WEB_URL + "member-pdex.html");
                break;
            default:
                break;
        }

    }

    /**
     * 加载网页
     *
     * @param path
     */
    private void load(String path) {
        Intent intent = null;
//        if (TextUtils.isEmpty(user_key)) {
//            intent = new Intent(context, LoginActivity.class);
//        } else {
            intent = new Intent(context, WebViewActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("flag", 001);
            bundle.putString("url", path);
            intent.putExtras(bundle);
//        }
        startActivity(intent);
    }

    @Override
    protected void RefreshData() {
        // TODO Auto-generated method stub

    }

}
